package com.leyou.item.controller;

import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.dto.SpuDetailDTO;
import com.leyou.item.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
public class GoodsController {


    @Autowired
    private GoodsService goodsService;

    /**
     * 分页查询spu
     *
     * @param page     当前页
     * @param rows     每页大小
     * @param saleable 上架商品或下降商品
     * @param key      关键字
     * @return 当前页商品数据
     */
    @GetMapping("spu/page")
    public ResponseEntity<PageResult<SpuDTO>> querySpuByPage(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "rows", defaultValue = "5") Integer rows,
            @RequestParam(value = "saleable", required = false) Boolean saleable,
            @RequestParam(value = "key", required = false) String key) {

        return ResponseEntity.ok(this.goodsService.querySpuByPage(page,rows,saleable,key));
    }

    @PostMapping("goods")
    public ResponseEntity<Void> addGoods(@RequestBody SpuDTO spuDTO){
        this.goodsService.save(spuDTO);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @GetMapping("spu/detail")
    public ResponseEntity<SpuDetailDTO> querySpuDetailById(@RequestParam("id")Long spuId){
        return ResponseEntity.ok(this.goodsService.querySpuDetailById(spuId));
    }

    @GetMapping("sku/of/spu")
    public ResponseEntity<List<SkuDTO>> querySkuBySpuId(@RequestParam("id")Long spuId){
        return ResponseEntity.ok(this.goodsService.querySkuBySpuId(spuId));
    }

    @PutMapping("spu/saleable")
    public ResponseEntity<Void> updateSaleable(
            @RequestParam("id")Long id,
            @RequestParam("saleable")Boolean saleable){

        this.goodsService.updateSaleable(id,saleable);

        return ResponseEntity.ok().build();//200表示修改成功
    }


    @PutMapping("goods")
    public ResponseEntity<Void> updateGoods(@RequestBody SpuDTO spuDTO){
        this.goodsService.updateGoods(spuDTO);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @GetMapping("spu/{id}")
    public ResponseEntity<SpuDTO> querySpuById(@PathVariable("id") Long id){
        return ResponseEntity.ok(goodsService.querySpuById(id));
    }

    @GetMapping("sku/list")
    public ResponseEntity<List<SkuDTO>> querySkuByIds(
            @RequestParam("ids")List<Long> ids) {
        return ResponseEntity.ok(this.goodsService.querySkuByIds(ids));
    }

    @PutMapping("/stock/minus")
    public ResponseEntity<Void> minusStock(@RequestBody Map<Long,Integer> cartMap){
        goodsService.minusStock(cartMap);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

}
